package com.mozz.finally_work.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mozz.finally_work.dao.BlogDao;
import com.mozz.finally_work.dao.UserDao;
import com.mozz.finally_work.pojo.Blog;
import com.mozz.finally_work.pojo.User;
import com.mozz.finally_work.utils.MybatisUtils;
import com.mozz.finally_work.utils.ParseMarkdown;
import org.apache.ibatis.session.SqlSession;
import org.pegdown.PegDownProcessor;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(name = "CodeBlogServlet", value = "/codeBlog")

public class CodeBlogServlet extends HttpServlet {
    private int pageSize = 10;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String page = request.getParameter("page");
        if (page == null || "".equals(page.trim())) {
            page = "1";
        }
        SqlSession session = MybatisUtils.getSession();
        BlogDao dao = session.getMapper(BlogDao.class);
        List<Blog> blogs;
        Integer max = null;
        if (page != null) {
            blogs = dao.queryAllBlogPage((Integer.parseInt(page)-1)*pageSize, pageSize);
            int count = dao.queryBlogCount();
            max = count / pageSize + 1;
        }else{
            // 调用dao查询
            blogs = dao.queryAllBlog();
        }
        response.setHeader("Content-Type", "text/html; charset=utf-8");
        for (Blog blog : blogs) {
            // 将 content由markdown转为html
            String parse = ParseMarkdown.parse(blog.getContent());
            blog.setContent(parse);
        }
        /*更新获取用户*/
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            UserDao userDao = session.getMapper(UserDao.class);
            User newUser = userDao.findUserById(user.getId());
            request.getSession().setAttribute("user", newUser);
        }
        session.close();
        request.setAttribute("blogs", blogs);
        request.setAttribute("max", max);
        request.setAttribute("page",page);
        request.getRequestDispatcher("blog.jsp").forward(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
